﻿namespace LiSAClient.WpfClient.Resources.Extensions
{
    using System.Windows;
    using System.Windows.Input;

    internal static class FrameworkElementExtensions
    {
        public static readonly DependencyProperty FocusFirstElementProperty =
           DependencyProperty.RegisterAttached(
                                        "FocusFirstElement",
                                        typeof(bool),
                                        typeof(FrameworkElementExtensions),
                                        new PropertyMetadata(default(bool), OnFocusFirstElementChanged));

        public static void SetFocusFirstElement(FrameworkElement e, bool value)
        {
            e.SetValue(FocusFirstElementProperty, value);
        }

        public static bool GetFocusFirstElement(FrameworkElement e)
        {
            return (bool)e.GetValue(FocusFirstElementProperty);
        }

        private static void OnFocusFirstElementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var element = d as FrameworkElement;
            if (element == null)
            {
                return;
            }

            if ((bool)e.NewValue)
            {
                element.Loaded += FocusFirstElement_Loaded;
            }
            else
            {
                element.Loaded -= FocusFirstElement_Loaded;
            }
        }

        private static void FocusFirstElement_Loaded(object sender, RoutedEventArgs e)
        {
            var element = sender as FrameworkElement;
            if (element == null)
            {
                return;
            }

            element.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
        }
    }

}
